<template>
  <el-dialog
    :visible.sync="visible"
    :title="title"
    :before-close="close"
    :close-on-click-modal="false"
    width="600px"
  >
    <el-form
      ref="form"
      :model="formData"
      :rules="rules"
      label-width="80px"
    >
      <el-form-item prop="username" label="用户名">
        <el-input v-model.trim="formData.username" :disabled="action === 'edit'" />
      </el-form-item>
      <el-form-item prop="name" label="姓名">
        <el-input v-model.trim="formData.name" />
      </el-form-item>
      <el-form-item prop="phone" label="手机号">
        <el-input v-model.trim="formData.phone" />
      </el-form-item>
      <el-form-item prop="sex" label="性别">
        <el-radio-group v-model="formData.sex">
          <el-radio :label="0">男</el-radio>
          <el-radio :label="1">女</el-radio>
        </el-radio-group>
      </el-form-item>
      <template v-if="action === 'add'">
        <el-form-item prop="password" label="初始密码">
          <el-input v-model.trim="formData.password" type="password" />
        </el-form-item>
        <el-form-item prop="confirmPass" label="确认密码">
          <el-input v-model.trim="formData.confirmPass" type="password" />
        </el-form-item>
      </template>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button
        :loading="btnLoading"
        type="primary"
        @click="confirm"
      >
        确定
      </el-button>
      <el-button
        @click="close"
      >
        取消
      </el-button>
    </div>
  </el-dialog>
</template>
<script>
import isMobilePhone from 'validator/lib/isMobilePhone'
import { cloneDeep } from 'lodash'
import http from '@/http.js'
const initForm = () => {
  return {
    username: '',
    name: '',
    phone: '',
    sex: 0,
    password: '',
    confirmPass: ''
  }
}
export default {
  data () {
    return {
      visible: false,
      action: 'add',
      formData: initForm(),
      btnLoading: false
    }
  },
  computed: {
    title () {
      return this.action === 'add' ? '新增用户' : '编辑用户'
    }
  },
  created () {
    const checkPhone = (rule, value, callback) => {
      if (!value || isMobilePhone(value, ['zh-CN'])) {
        callback()
      } else {
        callback(new Error('请输入合法手机号'))
      }
    }
    const checkConfirmPass = (rule, value, callback) => {
      if (value !== this.formData.password) {
        callback(new Error('密码不一致'))
      } else {
        callback()
      }
    }
    this.rules = {
      username: [
        { required: true, message: '请输入用户名' },
        { pattern: /^[a-zA-Z0-9_]*$/, message: '只允许输入_、大小写英文字母、数字' },
        { max: 32, message: '用户名最长不超过32个字符' }
      ],
      name: [
        { pattern: /^[\u4E00-\u9FA5]*$/, message: '姓名仅允许输入中文' },
        { max: 32, message: '姓名最长不超过32个字符' }
      ],
      phone: [
        { validator: checkPhone }
      ],
      password: [
        { required: true, message: '请输入初始密码' },
        { min: 8, message: '密码长度不能少于8位' },
        { max: 20, message: '密码长度不能超过20位' },
        { pattern: /^[^\u4E00-\u9FA5]*$/, message: '密码不允许输入中文' }
      ],
      confirmPass: [
        { required: true, message: '请确认密码' },
        { validator: checkConfirmPass }
      ]
    }
  },
  methods: {
    show (action, data) {
      this.action = action
      if (action === 'add') {
        this.formData = initForm()
      } else if (action === 'edit') {
        this.formData = cloneDeep(data)
      }
      this.visible = true
    },
    confirm () {
      this.$refs.form.validate(res => {
        if (res) {
          this.btnLoading = true
          if (this.action === 'add') {
            http.post('/user', this.formData)
              .then(() => {
                this.$message({ message: '操作成功', type: 'success' })
                this.$emit('success')
                this.close()
              })
              .finally(() => {
                this.btnLoading = false
              })
          } else {
            http.put(`/user/${this.formData._id}`, this.formData)
              .then(() => {
                this.$message({ message: '操作成功', type: 'success' })
                this.$emit('success')
                this.close()
              })
              .finally(() => {
                this.btnLoading = false
              })
          }
        }
      })
    },
    close () {
      this.formData = initForm()
      this.$nextTick(this.$refs.form.clearValidate)
      this.visible = false
    }
  }
}
</script>
